// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: daniel

#include "coin2/exchange/crypto/api_order/native_private_client.h"

#include <list>
#include <utility>

#include <fmt/format.h>

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/crypto/symbology/product.h"
#include "coin2/exchange/crypto_common/api_util/auth_key.h"
#include "coin2/exchange/order/crypto.pb.h"

CryptoNativePrivateClient::CryptoNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config) {
  mea_ = mea;
  NativeClientConfig cfg;
  cfg.set_rest_host("api.crypto.com");
  cfg.set_rest_host_port(443);
  cfg.MergeFrom(config);
  LOG(INFO) << "[CryptoNativePrivateClient] config: " << cfg.DebugString();
  auths_.Construct<CryptoRestAuth, NativeClientConfig>(cfg);
}

auto CryptoNativePrivateClient::QueryAccountBalance() -> HttpContextPtr {
  UrlParamsBuilder builder;
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_query_account_balance_, &builder);

  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  return HttpContextPtr(context);
}

auto CryptoNativePrivateClient::QueryOpenOrders() -> HttpContextPtr {
  UrlParamsBuilder builder;
  builder.PutPost("page_size", 200);
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_query_open_orders_, &builder);

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  return HttpContextPtr(context);
}

auto CryptoNativePrivateClient::QueryHistOrders() -> HttpContextPtr {
  UrlParamsBuilder builder;
  builder.PutPost("page_size", 200);
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_query_hist_orders_, &builder);

  context->query_type = OrderSubTopicId::REST_DONE_ORDERS;
  return HttpContextPtr(context);
}

auto CryptoNativePrivateClient::QueryTrades() -> HttpContextPtr {
  UrlParamsBuilder builder;
  builder.PutPost("page_size", 200);
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_query_trades_, &builder);

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  return HttpContextPtr(context);
}

auto CryptoNativePrivateClient::PlaceOrder(const RestParams& params) -> HttpContextPtr {
  UrlParamsBuilder builder;
  builder.PutPost("instrument_name", params.instrument_name());
  builder.PutPost("side", params.side());
  builder.PutPost("quantity", params.quantity());
  builder.PutPost("price", params.price());
  builder.PutPost("type", params.type());
  builder.PutPost("client_oid", params.client_oid());
  if (params.has_time_in_force()) {
    builder.PutPost("time_in_force", params.time_in_force());
  }
  if (params.has_exec_inst()) {
    builder.PutPost("exec_inst", params.exec_inst());
  }
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_place_order_, &builder);

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  return HttpContextPtr(context);
}

auto CryptoNativePrivateClient::CancelOrder(const RestParams& params) -> HttpContextPtr {
  UrlParamsBuilder builder;
  builder.PutPost("instrument_name", params.instrument_name());
  builder.PutPost("order_id", params.order_id());
  auto context = GetAuth()->CreateRequestByPostWithSignature(path_cancel_order_, &builder);

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  return HttpContextPtr(context);
}

auto CryptoNativePrivateClient::CancelAllOrder(const RestParams& params) -> HttpContextPtr {
  return {};
}

auto CryptoNativePrivateClient::PlaceOrderNorm(const OrderExecution& order_exe) -> HttpContextPtr {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

auto CryptoNativePrivateClient::CancelOrderNorm(const OrderExecution& order_exe) -> HttpContextPtr {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

auto CryptoNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id) -> RestParams {
  RestParams params;

  using coin2::exchange::crypto::symbology::CryptoProduct;
  auto product = CryptoProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  auto formatter = product_holder->product_info().order_formatter();
  params.set_client_oid(fmt::format("{}", proc_order_id));
  params.set_instrument_name(order_spec.product);
  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("BUY");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("SELL");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }
  params.set_quantity(formatter.FormatQty(order_spec.qty));
  if (order_spec.order_type == OrderType::LIMIT_ORDER) {
    params.set_type("LIMIT");
    params.set_price(formatter.FormatPrice(order_spec.price));
    if (order_spec.duration == coin::proto::OrderDuration::FOK_ORDER) {
      params.set_time_in_force("FILL_OR_KILL");
    } else if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
      params.set_time_in_force("IMMEDIATE_OR_CANCEL");
    } else {
      params.set_time_in_force("GOOD_TILL_CANCEL");
    }
  } else if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_type("MARKET");
  } else {
    NOTREACHED() << "unsupported order type: " << static_cast<int>(order_spec.order_type);
  }
  if (order_spec.post_only) {
    params.set_exec_inst("POST_ONLY");
  }

  return params;
}

auto CryptoNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  RestParams params;
  params.set_instrument_name(order_context.native_product());
  params.set_order_id(order_context.exchange_order_id());

  return params;
}

std::shared_ptr<AsioHttpContext> CryptoNativePrivateClient::SubmitOrderExecution(
    const OrderExecutionProto& order) {
  switch (order.type()) {
    case OrderExecutionProto::SUBMIT_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return PlaceOrder(params);
    }
    case OrderExecutionProto::CANCEL_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return CancelOrder(params);
    }
    default: {
      return nullptr;
    }
  }
}

std::shared_ptr<AsioHttpContext> CryptoNativePrivateClient::SubmitRestQuery(
    const RestQueryProto& query) {
  RestParams params;
  switch (query.type()) {
    case RestQueryProto::QUERY_ACCOUNT_BALANCE: {
      return QueryAccountBalance();
    }
    case RestQueryProto::QUERY_OPEN_ORDERS: {
      return QueryOpenOrders();
    }
    default: {
      return nullptr;
    }
  }
}
